package org.epidroid.epidroid.androsoul.ui.conversation;

import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;
import org.epidroid.epidroid.androsoul.engine.conversation.MessageItem;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulService;
import org.epidroid.epidroid.androsoul.ui.utils.TextFormater;

import android.content.Context;
import android.graphics.Color;
import android.text.ClipboardManager;
import android.text.SpannableString;
import android.text.method.LinkMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class ConversationMessageAdapter extends ArrayAdapter<MessageItem> {

	private List<MessageItem> _items;
	private ConversationActivity _context;
	private NetsoulContact _me = null;
	private IAndroSoulService _service = null;

	public ConversationMessageAdapter(NetsoulContact me, ConversationActivity context,
			int textViewResourceId, List<MessageItem> objects, IAndroSoulService service) {
		super(context, textViewResourceId, objects);
		this._me = me;
		_context = context;
		_items = objects;
		_service = service;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater inflater = (LayoutInflater) _context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.androsoul_message_item, null);
		}
		final MessageItem m = this._items.get(position);

		TextView content = (TextView) v.findViewById(R.id.list_item_title);

		String author = m.getAuthor();
		ForegroundColorSpan fg;
		if (author.equals(_me.getName())) {
			author = "me";
			fg = new ForegroundColorSpan(Color.BLUE);
		} else {
			fg = new ForegroundColorSpan(Color.RED);
		}

		SpannableString ss = SpannableString.valueOf(author + ": ");
		ss.setSpan(fg, 0, author.length() + 2, 0);
		content.setText(ss);
		content.append(TextFormater.getSpannable(_service, _context, m.getContent()));
		content.setMovementMethod(LinkMovementMethod.getInstance());
		Linkify.addLinks(content, Linkify.ALL);

		/*
		 * Set long click listener When we click on a message, we want to give
		 * the user the opportunity to copy the message in the clipboard.
		 */
		content.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				ClipboardManager clipboard = (ClipboardManager) _context
						.getSystemService(Context.CLIPBOARD_SERVICE);
				clipboard.setText(m.getContent());
				_context.showToast("The message has been copied to the clipboard!");
				return false;
			}

		});

		return (v);
	}
}
